// 数据库连接工具类
const mysql = require('mysql2/promise');
const dbConfig = require('../config/db');

class DatabaseConnection {
    constructor() {
        this.pool = null;
    }

    // 初始化数据库连接池
    async init() {
        try {
            // 验证必要的环境变量是否设置
            const requiredEnvVars = ['host', 'user', 'password', 'database'];
            const missingVars = requiredEnvVars.filter(varName => !dbConfig[varName]);
            
            if (missingVars.length > 0) {
                const errorMsg = `数据库配置不完整，缺少以下环境变量: ${missingVars.join(', ')} (请确保docker-compose.yml中已正确设置)`;
                console.error(errorMsg);
                throw new Error(errorMsg);
            }
            
            // 验证表配置信息
            if (!Array.isArray(dbConfig.tables) || dbConfig.tables.length === 0) {
                const errorMsg = '数据库表配置信息未正确设置或为空，请检查docker-compose.yml中的DB_TABLES环境变量';
                console.error(errorMsg);
                throw new Error(errorMsg);
            }
            
            this.pool = mysql.createPool({
                host: dbConfig.host,
                user: dbConfig.user,
                password: dbConfig.password,
                database: dbConfig.database,
                port: dbConfig.port,
                waitForConnections: true,
                connectionLimit: 10,
                queueLimit: 0
            });
            console.log('数据库连接池初始化成功');
            console.log(`成功加载 ${dbConfig.tables.length} 个表的配置信息`);
        } catch (error) {
            console.error('数据库连接失败:', error.message);
            // 特别处理JSON解析错误
            if (error instanceof SyntaxError && process.env.DB_TABLES) {
                console.error('表配置JSON格式错误，请检查docker-compose.yml中的DB_TABLES环境变量');
            }
            throw error;
        }
    }

    // 查询数据
    async query(sql, params = []) {
        if (!this.pool) {
            await this.init();
        }
        const [rows] = await this.pool.execute(sql, params);
        return rows;
    }

    // 获取表数据
    async getTableData(tableName) {
        // 从配置中获取表信息
        const tableConfig = dbConfig.tables.find(table => table.name === tableName);
        
        if (!tableConfig) {
            throw new Error(`表配置未找到: ${tableName}`);
        }
        
        // 构建查询字段列表，只查询配置中定义的字段
        const fields = tableConfig.columns.map(col => col.name).join(', ');
        const sql = `SELECT ${fields} FROM ${tableName}`;
        
        try {
            const data = await this.query(sql);
            return {
                data,
                structure: tableConfig
            };
        } catch (error) {
            console.error(`获取表 ${tableName} 数据失败:`, error);
            throw error;
        }
    }

    // 获取表结构信息
    getTableStructure(tableName) {
        const tableConfig = dbConfig.tables.find(table => table.name === tableName);
        if (!tableConfig) {
            throw new Error(`表配置未找到: ${tableName}`);
        }
        return tableConfig;
    }

    // 关闭连接池
    async close() {
        if (this.pool) {
            await this.pool.end();
        }
    }
}

module.exports = new DatabaseConnection();